import uuid from 'node-uuid'

import router from './_'
import pagination from '../lib/pagination'

router.get('/app', pagination, async (ctx, next) => {
  const page = ctx.state.page
  const data = await ctx.db.App.find(page.query)
                        .populate('user', { username: 1 })
                        .sort(page.sort)
                        .skip((page.page - 1) * page.limit)
                        .limit(page.limit)
  ctx.body = {
    meta: {
      page: page.page,
      limit: page.limit,
      count: await ctx.db.App.count(page.query),
      query: page,
    },
    items: data,
  }
})

router.get('/app/:code', async (ctx, next) => {
  // 按照应用ID查询应用信息
  const code = ctx.params.code
  const app = await ctx.db.App.findOne({ code: code })
  if (!app) {
    ctx.status = 422
    return ctx.body = {
      message: '应用不存在!'
    }
  }
  ctx.body = app
})

router.post('/app', async (ctx, next) => {
  const App = ctx.db.App
  const body = ctx.request.body
  body.code = uuid.v1()
  body.user = ctx.state.user._id
  ctx.body = await App.create(body)
})

export default router